from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models import CustomerUser
from app.models.goods import GoodsSku
from app.schemas.goods import GoodsSkuCreate,GoodsSkuUpdate


class SkuController(CRUDBase[GoodsSku, GoodsSkuCreate, GoodsSkuUpdate]):
    def __init__(self):
        super().__init__(model=GoodsSku)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        for item in data:
            item["select_nums"] = 0
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: GoodsSkuCreate):
        await self.create(obj_in=obj_in)
        return True

    async def do_update(self, obj_in: GoodsSkuUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, search: Q = Q()):
        await self.remove_q(search)
        return True

    async def get_price_by_user(self,sku_id:int,user_id:int=0):
        sku_data = await self.model.filter(id=sku_id).first().values("sku_level")
        try:
            print("获取价格开始")
            level = 1
            if user_id>0:
                customer = await CustomerUser.filter(id=user_id).first().values("role_id")
                if customer:
                    level = customer['role_id']
                    print(f"获取用户级别{level}")
            price = 0
            if sku_data:
                price = sku_data["sku_level"][level]
                print(f"获取用户级别价格{price}")
                if price is None:
                    price = sku_data["sku_level"][1]
                    print(f"未获取用户级别价格使用原价{price}")
        except Exception as e:
            price = sku_data["sku_level"][1]
            print(f"报错{e},使用原价{price}")
        return price

sku_controller =SkuController()
